﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class EJoyStick : MonoBehaviour,IPointerDownHandler,IPointerUpHandler {

    Camera mCamera;
    RectTransform center;
    bool pressDown;
    Vector2 centerPos;

    public event System.Action<Vector2> stickMoving;
    public event System.Action stickMoveEnd;

    private void Awake()
    {
        center = transform.Find("center") as RectTransform;
        mCamera = Camera.main;
    }

    void Update () {
        if (pressDown)
        {
            //屏幕坐标系转局部坐标系
            bool ret = RectTransformUtility.ScreenPointToLocalPointInRectangle(
                 transform as RectTransform,
                 Input.mousePosition,
                 mCamera, out centerPos);

            if (ret == false)
            {
                Debug.Log("遥感坐标转化失败");
                return;
            }

            //限制小圈的半径
            centerPos = Vector2.ClampMagnitude(centerPos,90);
            center.localPosition = centerPos;

            //通知观察者
            if (stickMoving != null)
            {
                stickMoving(centerPos.normalized);
            }
        }
	}

    public void OnPointerDown(PointerEventData eventData)
    {
        pressDown = true;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        pressDown = false;
        center.localPosition = Vector2.zero;
        if(stickMoveEnd!=null)
        {
            stickMoveEnd();
        }
    }

    //释放遥感
    public void Release()
    {
        OnPointerUp(null);
    }
}
